package org.example.xiaomi.controller;

import com.alibaba.fastjson.JSON;
import org.example.xiaomi.dao.impl.UserServiceImpl;

import org.example.xiaomi.service.UserService;
import org.example.xiaomi.util.RedisUtil;
import org.example.xiaomi.vo.ResultVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;



@WebServlet("/user/login")
public class UserController extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String captcha = req.getParameter("captcha");
        String verKey = req.getParameter("verKey");

        String redisCode = RedisUtil.getJedis().get(verKey);

        if (!redisCode.equalsIgnoreCase(captcha)) {
            resp.setContentType("application/json;charset=utf-8");
            PrintWriter out = resp.getWriter();
            out.print(JSON.toJSONString(ResultVO.fail("验证码不一致")));
            out.flush();
            out.close();
            return;
        }
        ResultVO resultVO = userService.findUserByNameAndPassword(username, password);
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println(JSON.toJSONString(resultVO));
        out.flush();
        out.close();
    }
}
